package org.example.controller;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Student;
import org.example.mapper.StudentMapper;
import org.example.plugins.GetDataSourceName;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequiredArgsConstructor
public class DynamicController {

    private final StudentMapper studentMapper;

    @GetMapping("/test")
    @Transactional
    public Object test(String id) {
        log.info("DynamicController..id :{}", id);
        Student student = new Student();
        student.setId(Long.parseLong(id));
        student.setName(UUID.randomUUID().toString());
        String dsKey = GetDataSourceName.get(id);
        DynamicDataSourceContextHolder.push(dsKey);
        studentMapper.insertStu(student);
        List<Student> students = studentMapper.queryAllStus();
        DynamicDataSourceContextHolder.clear();
        return students;
    }
}
